import { useEffect, useImperativeHandle } from "react";
import { Form, Input, InputNumber } from "antd";

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const UserForm = ({ref}) => {
  const [form] = Form.useForm();
  console.log(ref);

  // 初始化表单数据
  // useEffect(() => {
  //   if (initialValues) {
  //     form.setFieldsValue(initialValues);
  //   }
  // }, [form, initialValues]);

  const getFormData = () => {
    let formData = form.getFieldsValue();
    return formData;
  }

  // 将获取表单数据的方法暴露给父组件
  useImperativeHandle(ref, () => ({
    getFormData
  }))

  return (
    <Form
      form={form}
      {...formItemLayout}
      layout="horizontal"
    >
      <Form.Item
        name="name"
        label="姓名"
        rules={[
          { required: true, message: '请输入姓名' },
          { min: 2, message: '姓名至少2个字符' },
        ]}
      >
        <Input placeholder="请输入姓名" />
      </Form.Item>

      <Form.Item
        name="age"
        label="年龄"
        rules={[
          { required: true, message: '请输入年龄' },
          { type: 'number', min: 0, max: 1000, message: '年龄必须在18-120之间' },
        ]}
      >
        <InputNumber placeholder="请输入年龄" style={{ width: '100%' }} />
      </Form.Item>
    </Form>
  )
}

export default UserForm;